package com.cjr.mq.cases.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {
    public static final String DEAD_LETTER_EXCHANGE = "ex.waiting.dlx";
    public static final String DEAD_LETTER_ROUTING_KEY = "key.waiting.dlx";
    public static final String DEAD_LETTER_QUEUE = "queue.waiting.dlx";
    public static final String PAY_EXCHANGE = "ex.waiting";
    public static final String PAY_ROUTING_KEY = "key.waiting";
    public static final String PAY_QUEUE = "queue.waiting";

    // 声明业务队列
    @Bean
    public Queue queue() {
        Map<String,Object> argus =  new HashMap<>();
        // 消息的所有生存时间
        argus.put("x-message-ttl", 10000);
        // 关联死信交换器
        argus.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        // 关联死信交换器的routingkey
        argus.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY);
        return new Queue(PAY_QUEUE, true, false, false, argus);
    }
    // 死信队列
    @Bean
    public Queue queueDlx() {
        return new Queue(DEAD_LETTER_QUEUE, true, false, false, null);
    }

    // 声明业务交换器
    @Bean
    public Exchange exchanger() {
        return new DirectExchange(PAY_EXCHANGE, true, false, null);
    }
    // 死信交换器
    @Bean
    public Exchange exchangeDlx() {
        return new DirectExchange(DEAD_LETTER_EXCHANGE, true, false, null);
    }

    // 业务队列绑定到业务交换器
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(exchanger()).with(PAY_ROUTING_KEY).noargs();
    }
    // 死信队列绑定到死信交换器
    @Bean
    public Binding bindingDlx() {
        return BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with(DEAD_LETTER_ROUTING_KEY).noargs();
    }
}
